package com.investmenttechnologyservices.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;

public class JSONUtil {
	public static void toJSON(PrintWriter writer, Object o) throws IOException {
		if (o instanceof Collection) {
			toJSON(writer, (Collection<?>)o);
		} else if (o instanceof Entity) {
			toJSON(writer, (Entity)o);
		} else {
			if (o instanceof String) {
				writer.print('\"');
			}
			writer.print(o.toString());
			if (o instanceof String) {
				writer.print('\"');
			}
		}
	}

	private static void toJSON(PrintWriter writer, Collection<?> coll) throws IOException {
		writer.print("[");
		boolean first = true;
		for (Object element : coll) {
			if (!first) {
				writer.print(",");
			}
			first = false;
			toJSON(writer, element);
		}
		writer.print("]");
	}

	private static void toJSON(PrintWriter writer, Entity entity) throws IOException {
		writer.print("{");
		
		boolean first = true;

		Key key = entity.getKey();
		if (key.getId() != 0) {
			writer.print("\"id\":"+key.getId());
			first = false;
		} else if (key.getName() != null) {
			writer.print("\"id\":\""+key.getName()+"\"");
			first = false;
		}
		
		Map<String, Object> properties = entity.getProperties();
		for (Entry<String,Object> entry: properties.entrySet()) {
			if (!first) {
				writer.print(',');
			}
			first = false;
			writer.print('\"');
			writer.print(entry.getKey());
			writer.print('\"');
			writer.print(':');
			toJSON(writer, entry.getValue());
		}
		writer.print("}");
	}
}
